package com.lyrcsoft.springmvc.servlet;

import com.lyrcsoft.springmvc.init.handler.adapter.HandlerAdapter;
import com.lyrcsoft.springmvc.init.handler.mapping.HandlerMapping;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Map;

/**
 * @author fujc-dev@qq.com
 * @version 1.0
 */
public class DispatcherServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static Collection<HandlerAdapter> handlerAdapters;
    private static Collection<HandlerMapping> handlerMappings;

    public DispatcherServlet(ApplicationContext applicationContext) {
        // 组件的初始化
        Map<String, HandlerMapping> handlerMappingMap = applicationContext.getBeansOfType(HandlerMapping.class);
        handlerMappings = handlerMappingMap.values();

        Map<String, HandlerAdapter> handlerAdapterMap = applicationContext.getBeansOfType(HandlerAdapter.class);
        handlerAdapters = handlerAdapterMap.values();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object handlerMapping = getHandlerMapping(req);
        if (handlerMapping == null) {
            System.out.println("未匹配到handlerMapping");
            return;
        }
        HandlerAdapter handlerAdapter = getHandlerAdapter(handlerMapping);
        if (handlerAdapter == null) {
            System.out.println("未匹配到handlerAdapter");
            return;
        }
        Object result = handlerAdapter.handler(req, resp, handlerMapping);
        PrintWriter writer = resp.getWriter();
        writer.println(result);
        writer.flush();
        writer.close();

    }

    /**
     * 根据处理器找到适配器
     */
    private HandlerAdapter getHandlerAdapter(Object handlerMapping) {
        if (handlerAdapters != null) {
            for (HandlerAdapter adapter : handlerAdapters) {
                boolean flag = adapter.supports(handlerMapping);
                if (flag) {
                    return adapter;
                }
            }
        }
        return null;
    }

    /**
     * 找到适配器
     */
    private Object getHandlerMapping(HttpServletRequest req) {
        if (handlerMappings != null) {
            for (HandlerMapping handlerMapping : handlerMappings) {
                Object handler = handlerMapping.getHandlerMapping(req.getRequestURI());
                if (handler != null) {
                    return handler;
                }
            }
        }
        return null;
    }
}
